package com.kvn.backdoor.controller;

import com.kvn.backdoor.base.TableEnum;
import com.kvn.backdoor.base.XmlDbManager;
import com.kvn.backdoor.common.BackdoorErrorCode;
import com.kvn.backdoor.common.DbUtil;
import com.kvn.backdoor.common.OpResponse;
import com.kvn.backdoor.entity.BackdoorFunction;
import com.kvn.backdoor.entity.DbConfig;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.validation.constraints.NotNull;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzhiyuan on 2018/8/16
 */
@RestController
@RequestMapping("/function")
@Validated
public class FunctionManageController {

    @RequestMapping("/list")
    public OpResponse list(){
        List<BackdoorFunction> backdoorFunctions = new XmlDbManager().use(TableEnum.FUNCTION).selectList(BackdoorFunction.class);
        return OpResponse.suc(backdoorFunctions);
    }

    @RequestMapping("/save")
    public OpResponse save(@RequestBody @NotNull BackdoorFunction backdoorFunction) {
        if (backdoorFunction == null) {
            throw BackdoorErrorCode.ILLEGAL_PARAM.exp("backdoorFunction为空");
        }
        if (backdoorFunction.getId() == null) {
            new XmlDbManager().use(TableEnum.FUNCTION).insert(backdoorFunction);
        } else {
            new XmlDbManager().use(TableEnum.FUNCTION).updateById(backdoorFunction);
        }

        return OpResponse.suc();
    }

    @RequestMapping("/delete")
    public OpResponse delete(@NotEmpty String id) {
        new XmlDbManager().use(TableEnum.FUNCTION).deleteById(id);
        return OpResponse.suc();
    }

    @RequestMapping("/executeSql")
    public OpResponse executeSql(@SessionAttribute(value = "dbConfig", required = false) DbConfig dbConfig,@NotEmpty String sql) {
        if (dbConfig == null) {
            throw BackdoorErrorCode.DB_CONFIG_ISNULL.exp();
        }

        // 支持多个sql同时执行
        String[] sqlArr = sql.split(";");
        return OpResponse.suc(DbUtil.use(dbConfig).executeBatch(sqlArr));
    }


}
